package com.pig4cloud.pig.module.controller.property;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.pig4cloud.pig.common.core.util.DateUtils;
import com.pig4cloud.pig.common.core.util.OkHttpClientUtil;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.log.annotation.SysLog;
import com.pig4cloud.pig.common.mybatis.page.PageUtils;
import com.pig4cloud.pig.common.mybatis.page.TableDataInfo;
import com.pig4cloud.pig.common.security.service.PigUser;
import com.pig4cloud.pig.common.security.util.SecurityUtils;
import com.pig4cloud.pig.module.api.entity.estate.Estate;
import com.pig4cloud.pig.module.api.entity.property.PropertyFeeOrder;
import com.pig4cloud.pig.module.api.entity.property.PropertyFeeOrderInfo;
import com.pig4cloud.pig.module.api.entity.property.PropertyFeeOrderTemplate;
import com.pig4cloud.pig.module.api.entity.wx.WxUser;
import com.pig4cloud.pig.module.service.estate.IEstateService;
import com.pig4cloud.pig.module.service.property.IPropertyFeeOrderInfoService;
import com.pig4cloud.pig.module.service.property.IPropertyFeeOrderService;
import com.pig4cloud.pig.module.service.property.IPropertyFeeOrderTemplateService;
import com.pig4cloud.pig.module.service.property.IPropertyService;
import com.pig4cloud.pig.module.service.wx.IWxTemplateService;
import com.pig4cloud.pig.module.service.wx.IWxUserService;
import com.vdurmont.emoji.EmojiParser;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;

/**
 * 物业费订单Controller
 *
 * @author ruoyi
 * @date 2021-08-24
 */
@Validated
@Api(value = "物业费订单控制器", tags = {"物业费订单管理"})
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@RestController
@RequestMapping("/property/order")
public class PropertyFeeOrderController {

    private final IPropertyFeeOrderService propertyFeeOrderService;
    private final IPropertyService propertyService;
    private final IEstateService estateService;
	private final IWxUserService wxUserService;
    private final IWxTemplateService wxTemplateService;
	private final IPropertyFeeOrderInfoService propertyFeeOrderInfoService;
	private final IPropertyFeeOrderTemplateService feeOrderTemplateService;
	private final IPropertyFeeOrderTemplateService propertyFeeOrderTemplateService;

//	@Value("${ruoyi.imgUrl}")
//	private String imgUrl;

	@Value("${ruoyi.imgUrlOss}")
	private String imgUrlOss;

    /**
     * 查询物业费订单列表
     */
    @ApiOperation("查询物业费订单列表")
    @PreAuthorize("@pms.hasPermission('module:propertyorder:list')")
    @GetMapping("/list")
    public TableDataInfo<PropertyFeeOrder> list(@Validated PropertyFeeOrder propertyFeeOrder) {
        PigUser sysUser = SecurityUtils.getUser();
        QueryWrapper<PropertyFeeOrder> qw = new QueryWrapper<>();
        if(sysUser.getUserType() == 2){//物业公司
            qw.eq("property_id",sysUser.getPropertyId());
			if(propertyFeeOrder.getEstateId()!=null){
				qw.eq("estate_id",propertyFeeOrder.getEstateId());
			}
        } else if(sysUser.getUserType() == 3){//小区
            qw.eq("estate_id",sysUser.getEstateId());
        } else{
        	if(propertyFeeOrder.getPropertyId()!=null){
				qw.eq("property_id",propertyFeeOrder.getPropertyId());
			}

			if(propertyFeeOrder.getEstateId()!=null){
				qw.eq("estate_id",propertyFeeOrder.getEstateId());
			}
		}

		qw.eq("is_del", 0);
		if(propertyFeeOrder.getPayPlatform()!=null){
			qw.eq("pay_platform",propertyFeeOrder.getPayPlatform());
		}
        if(StrUtil.isNotEmpty(propertyFeeOrder.getOrderNo())){
        	qw.and(wrapper->{
				wrapper.like("phone_num",propertyFeeOrder.getOrderNo())
                    .or().like("room_no",propertyFeeOrder.getOrderNo())
					.or().like("order_no",propertyFeeOrder.getOrderNo())
					.or().like("out_trade_no",propertyFeeOrder.getOrderNo());
			});
        }

        if(StrUtil.isNotEmpty(propertyFeeOrder.getBeginDate())){
            qw.between("create_time",propertyFeeOrder.getBeginDate() + " 00:00:00",propertyFeeOrder.getEndDate() + " 23:59:59");
        }

        if(propertyFeeOrder.getState() != null){
            qw.eq("state",propertyFeeOrder.getState());
        }

        qw.orderByDesc("create_time");
        TableDataInfo<PropertyFeeOrder> td = PageUtils.buildDataInfo(propertyFeeOrderService.page(PageUtils.buildPage(),qw));
        List<PropertyFeeOrder> list = td.getData();
        list.forEach(order->{

			if(StrUtil.isNotEmpty(order.getReceiptImgUrl())){
				order.setReceiptImgUrlPath(imgUrlOss + order.getReceiptImgUrl());
			}

            if(StrUtil.isNotEmpty(order.getNickName())){
            	order.setNickName(EmojiParser.parseToUnicode(order.getNickName()));
			}
        });

        Map<String,Object> map = new HashMap<>();
		if(sysUser.getUserType() == 2){//物业公司
			map.put("property_id",sysUser.getPropertyId());
		} else if(sysUser.getUserType() == 3){//小区
			map.put("estate_id",sysUser.getEstateId());
		} else{
			if(propertyFeeOrder.getPropertyId()!=null){
				map.put("property_id",propertyFeeOrder.getPropertyId());
			}
			if(propertyFeeOrder.getEstateId()!=null){
				map.put("estate_id",propertyFeeOrder.getEstateId());
			}
		}
		if(propertyFeeOrder.getPayPlatform()!=null){
			map.put("pay_platform",propertyFeeOrder.getPayPlatform());
		}
		if (propertyFeeOrder.getEstateId()!=null){
			map.put("estate_id",propertyFeeOrder.getEstateId());
		}
		if(StrUtil.isNotEmpty(propertyFeeOrder.getBeginDate())){
			map.put("begin_time",propertyFeeOrder.getBeginDate() + " 00:00:00");
			map.put("end_time",propertyFeeOrder.getEndDate() + " 23:59:59");
		}
		PropertyFeeOrder feeOrder = propertyFeeOrderService.selectOrderTongjiByEstateId(map);

		Map<String,Object> mapOther = new HashMap<>();
		mapOther.put("feeOrder",feeOrder);
		mapOther.put("userId", sysUser.getId());
		td.setOtherData(mapOther);
        return td;
    }

    /**
     * 导出物业费订单列表
     */
    @ApiOperation("导出物业费订单列表")
    @PreAuthorize("@pms.hasPermission('module:propertyorder:export')")
    @SysLog("物业费订单")
    @GetMapping("/export")
    public List export(@Validated PropertyFeeOrder propertyFeeOrder) {
		PigUser sysUser = SecurityUtils.getUser();
		QueryWrapper<PropertyFeeOrder> qw = new QueryWrapper<>();
		if(sysUser.getUserType() == 2){//物业公司
			qw.eq("property_id",sysUser.getPropertyId());
		} else if(sysUser.getUserType() == 3){//小区
			qw.eq("estate_id",sysUser.getEstateId());
		} else{
			if(propertyFeeOrder.getPropertyId()!=null){
				qw.eq("property_id",propertyFeeOrder.getPropertyId());
			}

			if(propertyFeeOrder.getEstateId()!=null){
				qw.eq("estate_id",propertyFeeOrder.getEstateId());
			}
		}
		if(propertyFeeOrder.getEstateId()!=null){
			qw.eq("estate_id",propertyFeeOrder.getEstateId());
		}
		if(propertyFeeOrder.getPayPlatform()!=null){
			qw.eq("pay_platform",propertyFeeOrder.getPayPlatform());
		}
		//订单状态   0 - 交费申请 1 - 已生成交费清单    2 - 待支付  3- 支付中  4 - 已支付 5 - 订单取消
		qw.eq("state",4);
		if(StrUtil.isNotEmpty(propertyFeeOrder.getPhoneNum())){
			qw.eq("phone_num",propertyFeeOrder.getPhoneNum());
		}

		qw.eq("is_del", 0);
		if(StrUtil.isNotEmpty(propertyFeeOrder.getBeginDate())){
			qw.between("create_time",propertyFeeOrder.getBeginDate() + " 00:00:00",propertyFeeOrder.getEndDate() + " 23:59:59");
		}

        List<PropertyFeeOrder> list = propertyFeeOrderService.list(qw);
		if(CollUtil.isNotEmpty(list)){
			for (PropertyFeeOrder feeOrder : list){
				if(feeOrder.getPayTime()!=null){
					feeOrder.setPayTimeStr(DateUtils.getTime(feeOrder.getPayTime()));
				}
				//订单状态   0 - 交费申请 1 - 已生成交费清单    2 - 待支付  3- 支付中  4 - 已支付 5 - 订单取消
				if(feeOrder.getState() == 0){
					feeOrder.setStateStr("交费已申请");
				} else if(feeOrder.getState() == 1){
					feeOrder.setStateStr("已生成交费清单");
				} else if(feeOrder.getState() == 2){
					feeOrder.setStateStr("待支付");
				} else if(feeOrder.getState() == 3){
					feeOrder.setStateStr("支付中");
				} else if(feeOrder.getState() == 4){
					feeOrder.setStateStr("已支付");
				} else if(feeOrder.getState() == 5){
					feeOrder.setStateStr("订单取消");
				}

				if(StrUtil.isNotEmpty(feeOrder.getNickName())){
					feeOrder.setNickName(EmojiParser.parseToUnicode(feeOrder.getNickName()));
				}

				feeOrder.setWyfMonths("0个月");
				feeOrder.setWaterMonths("0个月");
				feeOrder.setElectricMonths("0个月");
				feeOrder.setCarMonths("0个月");
				feeOrder.setWaterNum("0m³");

				QueryWrapper<PropertyFeeOrderInfo> qwInfo = new QueryWrapper<>();
				qwInfo.eq("order_id",feeOrder.getId());
				List<PropertyFeeOrderInfo> orderInfos = propertyFeeOrderInfoService.list(qwInfo);
				if(CollUtil.isNotEmpty(orderInfos)){
					for (PropertyFeeOrderInfo orderInfo : orderInfos){
						String beginMonth = DateUtils.getYearMonthTime(orderInfo.getBeginDate());
						String endMonth = DateUtils.getYearMonthTime(orderInfo.getEndDate());
						String months = beginMonth + " ~ " + endMonth;// + " " +orderInfo.getMonthCount()+"个月";
						if(orderInfo.getFeeType().equals("wyf")){
							feeOrder.setWyfMonths(months);
						} else if(orderInfo.getFeeType().equals("water")){
//							String beginMon = DateUtils.getMonthTime(orderInfo.getBeginDate());
//							String beginYea = DateUtils.getYeaTime(orderInfo.getBeginDate());
//							String endMon = DateUtils.getMonthTime(orderInfo.getEndDate());
//							String endYea = DateUtils.getYeaTime(orderInfo.getEndDate());
//							QueryWrapper<PropertyFeeOrderTemplate> qwBegin = new QueryWrapper();
//							qwBegin.eq("year_num",beginYea);
//							qwBegin.eq("month_num",beginMon);
//							qwBegin.eq("room_no",feeOrder.getRoomNo());
//							TableDataInfo<PropertyFeeOrderTemplate> waterBegin=PageUtils.buildDataInfo(propertyFeeOrderTemplateService.page(PageUtils.buildPage(),qwBegin));
//							List<PropertyFeeOrderTemplate> list1=waterBegin.getRows();
//							String begin = "";
//							String end = "";
//							for (PropertyFeeOrderTemplate list2:list1){
//								if (list2.getBeginCount()!=null){
//									begin = list2.getBeginCount().longValue()+"m³";
//								}
//							}
//							QueryWrapper<PropertyFeeOrderTemplate> qwEnd = new QueryWrapper();
//							qwEnd.eq("year_num",endYea);
//							qwEnd.eq("month_num",endMon);
//							qwEnd.eq("room_no",feeOrder.getRoomNo());
//							TableDataInfo<PropertyFeeOrderTemplate> waterEnd=PageUtils.buildDataInfo(propertyFeeOrderTemplateService.page(PageUtils.buildPage(),qwBegin));
//							List<PropertyFeeOrderTemplate> list3=waterEnd.getRows();
//							for (PropertyFeeOrderTemplate list4:list3){
//								if (list4.getEndCount()!=null){
//									end = list4.getEndCount().longValue()+"m³";
//								}
//							}
//							String num = begin+"-"+end;
//							feeOrder.setWaterNum(num);
							feeOrder.setWaterMonths(months);
						} else if(orderInfo.getFeeType().equals("eletrict")){
							feeOrder.setElectricMonths(months);
						} else if(orderInfo.getFeeType().equals("car")){
							feeOrder.setCarMonths(months);
						}
					}
				}
			}
		}
        // ExcelUtil<PropertyFeeOrder> util = new // ExcelUtil<>(PropertyFeeOrder.class);
        return  list;// util.exportExcel(list, "物业费订单");
    }

    /**
     * 获取物业费订单详细信息
     */
    @ApiOperation("获取物业费订单详细信息")
    @PreAuthorize("@pms.hasPermission('module:propertyorder:query')")
    @GetMapping("/{id}")
    public R<PropertyFeeOrder> getInfo(@NotNull(message = "主键不能为空") @PathVariable("id") Long id) {
        PropertyFeeOrder propertyFeeOrder = propertyFeeOrderService.getById(id);
        if(propertyFeeOrder != null) {
            Date[] date = new Date[]{ propertyFeeOrder.getBeginTime(), propertyFeeOrder.getEndTime() };
            propertyFeeOrder.setDateRangeTime(date);
            Estate estate = estateService.findById(propertyFeeOrder.getEstateId());
			propertyFeeOrder.setEstate(estate);

			WxUser wxUser = wxUserService.findById(propertyFeeOrder.getUserId());
			List<WxUser> wxUserList = new ArrayList<>();
			if(wxUser!=null){
				wxUserList.add(wxUser);
			}
			propertyFeeOrder.setWxUsers(wxUserList);

			if(StrUtil.isNotEmpty(propertyFeeOrder.getReceiptImgUrl())){
				propertyFeeOrder.setReceiptImgUrlPath(imgUrlOss + propertyFeeOrder.getReceiptImgUrl());
			}

			QueryWrapper<PropertyFeeOrderInfo> qw = new QueryWrapper<>();
			qw.eq("order_id",propertyFeeOrder.getId());
			qw.orderByAsc("end_date");
			List<PropertyFeeOrderInfo> orderInfoList = propertyFeeOrderInfoService.list(qw);
			if(CollUtil.isNotEmpty(orderInfoList)){
				for (PropertyFeeOrderInfo orderInfo : orderInfoList){
					if(orderInfo.getBeginDate()!=null){
						orderInfo.setBeginMonth(DateUtils.getYearMonthTime(orderInfo.getBeginDate()));
					}
					if(orderInfo.getEndDate()!=null){
						orderInfo.setEndMonth(DateUtils.getYearMonthTime(orderInfo.getEndDate()));
					}
				}
			}
			propertyFeeOrder.setOrderInfoList(orderInfoList);

			QueryWrapper<PropertyFeeOrderTemplate> qwTemplate = new QueryWrapper<>();
			qwTemplate.eq("fee_order_id",propertyFeeOrder.getId());
            qwTemplate.orderByAsc("year_num");
            qwTemplate.orderByAsc("month_num");
			List<PropertyFeeOrderTemplate> templates = feeOrderTemplateService.list(qwTemplate);
			propertyFeeOrder.setTemplates(templates);
		}
        return R.ok(propertyFeeOrder);
    }


    /**
     * 获取物业费订单详细信息
     */
    @ApiOperation("获取物业费订单详细信息")
    @PreAuthorize("@pms.hasPermission('module:propertyorder:query')")
    @GetMapping("/queryOrder/{id}")
    public R<PropertyFeeOrder> queryOrder(@NotNull(message = "主键不能为空") @PathVariable("id") Long id) {
        PropertyFeeOrder propertyFeeOrder = propertyFeeOrderService.getById(id);
        if(propertyFeeOrder != null) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.set("order_id",propertyFeeOrder.getId());
            jsonObject.set("user_id",propertyFeeOrder.getUserId());

            String url = "https://api.sdyuedou.com/ydapi/property/order/query";
            try {
                OkHttpClientUtil.getInstance().postJson(url,jsonObject.toString());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return R.ok(propertyFeeOrder);
    }


    /**
     * 新增物业费订单
     */
    @ApiOperation("新增物业费订单")
    @PreAuthorize("@pms.hasPermission('module:propertyorder:add')")
    @SysLog("物业费订单")

    @PostMapping()
    public R<Void> add(@Valid @RequestBody PropertyFeeOrder propertyFeeOrder) {
        String orderNo = "E" + propertyFeeOrder.getEstateId() + DateUtils.dateTimeNow();
        if(propertyFeeOrder.getDateRange()!=null){
            String[] range = propertyFeeOrder.getDateRange();
            if(range.length == 2){
                propertyFeeOrder.setBeginTime(DateUtils.parseDate(range[0]));
                propertyFeeOrder.setEndTime(DateUtils.parseDate(range[1]));
            }
        }

        if(propertyFeeOrder.getUserId()!=null){
            WxUser wxUser = wxUserService.findById(propertyFeeOrder.getUserId());
            if(wxUser!=null){
                propertyFeeOrder.setNickName(EmojiParser.parseToUnicode(wxUser.getNickName()));
            }
        }
        if(propertyFeeOrder.getElectricFee() == null){
            propertyFeeOrder.setElectricFee(new BigDecimal(0));
        }
        if(propertyFeeOrder.getTrashFee() == null){
            propertyFeeOrder.setTrashFee(new BigDecimal(0));
        }
        if(propertyFeeOrder.getWaterFee() == null){
            propertyFeeOrder.setWaterFee(new BigDecimal(0));
        }

        propertyFeeOrder.setOrderNo(orderNo);
        propertyFeeOrder.setOutTradeNo(orderNo);
        propertyFeeOrder.setUseIntegral(0d);
        propertyFeeOrder.setDkRate(0);
        propertyFeeOrder.setCreateTime(new Date());
        propertyFeeOrder.setState(1);

        Estate estate = estateService.findById(propertyFeeOrder.getEstateId());
        if(estate!=null){
            propertyFeeOrder.setPropertyId(estate.getPropertyId());
        }
        double totalMoney = 0;
        if(propertyFeeOrder.getWyfFee()!=null){
            totalMoney += propertyFeeOrder.getWyfFee().doubleValue();
        }
        if(propertyFeeOrder.getTrashFee()!=null){
            totalMoney += propertyFeeOrder.getTrashFee().doubleValue();
        }
        if(propertyFeeOrder.getWaterFee()!=null){
            totalMoney += propertyFeeOrder.getWaterFee().doubleValue();
        }
        if(propertyFeeOrder.getElectricFee()!=null){
            totalMoney += propertyFeeOrder.getElectricFee().doubleValue();
        }
        propertyFeeOrder.setTotalMoney(new BigDecimal(totalMoney));
        propertyFeeOrder.setPayMoney(new BigDecimal(totalMoney));

        return R.okByRow(propertyFeeOrderService.save(propertyFeeOrder) ? 1 : 0);
    }

    /**
     * 修改物业费订单
     */
    @ApiOperation("修改物业费订单")
    @PreAuthorize("@pms.hasPermission('module:propertyorder:edit')")
    @SysLog("物业费订单")

    @PutMapping()
    public R<Void> edit(@Valid @RequestBody PropertyFeeOrder propertyFeeOrder) {

//    	PigUser sysUser = SecurityUtils.getUser();
//    	if(propertyFeeOrder.getState() >= 4){
//			return R.failed("订单已支付成功");
//		}

//        String orderNo = "E" + propertyFeeOrder.getEstateId() + DateUtils.dateTimeNow();
//        if(propertyFeeOrder.getDateRange()!=null){
//            String[] range = propertyFeeOrder.getDateRange();
//            if(range.length == 2){
//                propertyFeeOrder.setBeginTime(DateUtils.parseDate(range[0]));
//                propertyFeeOrder.setEndTime(DateUtils.parseDate(range[1]));
//            }
//        }

//        if(propertyFeeOrder.getElectricFee() == null){
//            propertyFeeOrder.setElectricFee(new BigDecimal(0));
//        }
//        if(propertyFeeOrder.getTrashFee() == null){
//            propertyFeeOrder.setTrashFee(new BigDecimal(0));
//        }
//        if(propertyFeeOrder.getWaterFee() == null){
//            propertyFeeOrder.setWaterFee(new BigDecimal(0));
//        }

//        propertyFeeOrder.setOrderNo(orderNo);
//        propertyFeeOrder.setOutTradeNo(orderNo);
//        propertyFeeOrder.setUseIntegral(0d);
//        propertyFeeOrder.setDkRate(0);
        // 订单状态   0 - 交费申请 1 - 已生成交费清单 2 - 待支付  3- 支付中  4 - 已支付 5 - 订单取消
//		if(propertyFeeOrder.getSaveType() == 0){//单纯保存
//			propertyFeeOrder.setState(1);
//		}else if(propertyFeeOrder.getSaveType() == 1){
//			propertyFeeOrder.setState(2);
//		}

		PropertyFeeOrder propertyFeeOrder1 = propertyFeeOrderService.findById(propertyFeeOrder.getId());
		if(propertyFeeOrder1!=null){
			propertyFeeOrder1.setRemark(propertyFeeOrder.getRemark());
		}
        int ret = propertyFeeOrderService.updateById(propertyFeeOrder1) ? 1 : 0;
        if(ret > 0){
//            WxUser wxUser = wxUserService.findById(propertyFeeOrder.getUserId());
//            if(wxUser!=null){
//				if(propertyFeeOrder.getSaveType() == 1){
//					wxTemplateService.sendWxMsgByPropertyFee(wxUser,propertyFeeOrder);
//				}
//            }
        }
        return R.okByRow(ret);
    }


	/**
	 * 订单退款
	 */
	@ApiOperation("订单退款")
	@PreAuthorize("@pms.hasPermission('module:chargerorder:edit')")
	@SysLog("订单退款")

	@PostMapping("/refundOrder")
	public R<Void> refundOrder(@Valid @RequestBody PropertyFeeOrder chargerOrder) {
		int ret = 0;// propertyFeeOrderService.refundOrder(chargerOrder);
		return R.okByRow(ret);
	}

    /**
     * 删除物业费订单
     */
    @ApiOperation("删除物业费订单")
    @PreAuthorize("@pms.hasPermission('module:propertyorder:remove')")
    @SysLog("物业费订单")
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")  @PathVariable Long[] ids) {
    	for (Long id : ids){
    		PropertyFeeOrder order = propertyFeeOrderService.findById(id);
    		if(order != null){
    			order.setIsDel(1);
				propertyFeeOrderService.updateById(order);
			}
		}
        return R.okByRow(1);
    }
}
